import time
import datetime
from wx.lib.pubsub import setuparg1
from wx.lib.pubsub import pub

import DataManager

class ModelRecord():
    #views must refresh their UI on receiving this
    M_REFRESH = "RECORD_REFRESH"
    select_stm = "select type, start, end, rating, mood from record where \
start >= %d and end <= %d"

    def __init__(self):
        now = datetime.datetime.now().date()
        self.do_load(now, now + datetime.timedelta(1))

    def load(self, start, end):
        self.do_load(start, end)
        self.refresh()
        
    def do_load(self, start, end):
        #this method is used when time reference or time mode is changed
        #this name is horriblly long
        sn = datetime.datetime.fromtimestamp
        self.start = start
        self.end = end
        #change start end into stamp format
        start = time.mktime(start.timetuple())
        end = time.mktime(end.timetuple())
        ret = DataManager.DataManager.db.querry(self.select_stm%(start, end))
        #should be processed, start end changed into datetime format
        self.data = [(i[0], sn(i[1]), sn(i[2]), i[3], i[4]) for i in ret]


    def refresh(self):
        pub.sendMessage(self.M_REFRESH, data=None)

    def merge(self, d):
        if d['status'] == 1:
            #delete case
            DataManager.DataManager.db.delete('record', 'ct == %d'%(d['ctime']))
        else:
            #add case
            DataManager.DataManager.db.add('record', '(%s, %d, %d, %d, %d, %d, %d, %d)'
                                           %(d['kind'], d['start'], d['end'], d['rating'],
                                             d['mood'], d['status'], d['ctime'], d['mtime']))
